const Router = require('koa-router')
const router = new Router()
const { login } = require('../controller/users')
const { SuccessModel, ErrorModel } = require('../model/resModel')

router.prefix('/users') // 路由前缀

// 登录
router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body
  const userData = await login(username, password)
  if (userData.length > 0) {
    ctx.session.username = username
    ctx.body = new SuccessModel('登录成功')
  } else {
    ctx.body = new ErrorModel('登录失败')
  }
})

router.get('/session-test', async (ctx, next) => {
  if (ctx.session.username) {
    ctx.body = new SuccessModel('已登录')
    return
  }
  ctx.body = new ErrorModel('未登录')
})

module.exports = router